# -*- coding: utf-8 -*-

from odoo import http
import urllib
import urllib2
import json

from odoo.http import request
import logging
from datetime import datetime, timedelta, time
import pytz

_logger = logging.getLogger(__name__)


class authentication(http.Controller):

    # 订阅平台数据回调接口
    @http.route('/watermeter/subscription/callbacks', auth='public', csrf=False)
    def subscribecallback1(self, **kwargs):

        return "hello world!"

    @http.route('/watermeter/adddata', auth='public', csrf=False)
    def subscribecallback(self, **kw):
        if not kw:
            _logger.info(u"没有参数")
            back = '{"callback": "没有有参数"}'
            return json.dumps(back)
        else:
            _logger.info(u"**************************************************有参数")
            # return "++++++++++++"
            # _logger.info(kw)
            deviceId = kw.get('deviceId')
            return deviceId
            # _logger.info(deviceId)
            # service = kw.get('service')
            # deviceData = service.get('data')
            #
            # table_no = deviceData.get('meterNumber')
            # balance = deviceData.get('accountBalance')
            # sum_of_amount = deviceData.get('totalAmount')
            # sum_of_flow = deviceData.get('meterValue')
            # table_state = deviceData.get('meterStatus')
            #
            # sql = "update watermeters_watermeter set table_no='%s',balance=%s,sum_of_amount=%s," \
            #       "sum_of_flow=%s,table_state='%s' " \
            #       "from watermeters_watermeter a where a.device_id='%s'" % (
            #           table_no, balance, sum_of_amount, sum_of_flow, table_state, deviceId)
            # request.env.cr.execute(sql)
            # return True

    @http.route('/watermeter/subscription/callback', auth='none', csrf=False, type='json')
    def subscriptioncallback(self, request, **kw):
        try:
            params = request.jsonrequest
            # params = json.dumps(params)
            device_id = params.get('deviceId')
            service = params.get('service')
            time = service.get('eventTime')
            tz = pytz.timezone('Asia/Shanghai')
            utctime = datetime(int(time[0:4]), int(time[4:6]), int(time[6:8]), int(time[9:11]), int(time[11:13]),
                               int(time[13:15]), tzinfo=pytz.timezone('UTC'))
            upload_time = utctime.astimezone(tz).strftime("%Y-%m-%d %H:%M:%S")
            data = service.get('data')
            table_no = data.get('meterNumber')
            balance = data.get('accountBalance')
            sum_of_amount = data.get('totalAmount')
            table_state = data.get('meterStatus')
            sum_of_flow = data.get('meterValue')

            watermeter = http.request.env['watermeters.watermeter'].sudo().search([
                ('device_id', '=', device_id),
            ], limit=1)
            if watermeter:
                # 更新数据
                watermeter.sudo().write({
                    'upload_time': upload_time,
                    'table_state': table_state,
                    'sum_of_flow': sum_of_flow,
                    'sum_of_amount': sum_of_amount,
                    'balance': balance,
                    'table_no': table_no,
                })
                # 写进test日志
                http.request.env['watermeters.test'].sudo().create({
                    'watermeter_id': watermeter.id,
                    'table_no': table_no,
                    'balance': balance,
                    'sum_of_amount': sum_of_amount,
                    'sum_of_flow': sum_of_flow,
                    'table_state': table_state,
                    'device_id': device_id,
                    'upload_time': upload_time,
                    'IMEI': watermeter.IMEI
                })
            else:
                raise UserError('设备号为%s的设备不存在！' % device_id)
                # meter = http.request.env['watermeters.watermeter'].sudo().create({
                #     'table_no': table_no,
                #     'balance': balance,
                #     'sum_of_amount': sum_of_amount,
                #     'sum_of_flow': sum_of_flow,
                #     'table_state': table_state,
                #     'device_id': device_id,
                #     'upload_time': upload_time,
                #     'IMEI': '0'
                # })
                # http.request.env['watermeters.test'].sudo().create({
                #     'watermeter_id': meter.id,
                #     'table_no': table_no,
                #     'balance': balance,
                #     'sum_of_amount': sum_of_amount,
                #     'sum_of_flow': sum_of_flow,
                #     'table_state': table_state,
                #     'device_id': device_id,
                #     'upload_time': upload_time,
                #     'IMEI': meter.IMEI
                # })
        except Exception, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                _logger.info(error)

    @http.route('/test', auth='none', csrf=False)
    def test(self, **kw):
        try:
            _logger.info(kw)
            list = kw.get('list')
            _logger.info(list)
            _logger.info(str(type(list)))
            list = json.loads(list)
            _logger.info(list)
            _logger.info(str(type(list)))
        except Excepttion, e:
            try:
                error = e[0]
            except:
                error = str(e)
            finally:
                return json.dumps({
                    'success': False,
                    'code': 500,
                    'message': error
                })
